#include <QToolButton>
#include <QKeyEvent>
#include <QThread>
#include <QLineEdit>
#include <QPainter>
#include <QTextCodec>
#include "dataprovider.h"
#include "mytoolbutton.h".h"

//重载QToolButton,增加上下左右和首个子控件属性
MyToolButton::MyToolButton(QWidget *parent) :
    QToolButton(parent)
{
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForCStrings(codec);
    QTextCodec::setCodecForTr(codec);
    QTextCodec::setCodecForLocale(codec);

    //this->slider = NULL;
    this->upWg = NULL;
    this->downWg = NULL;
    this->leftWg =NULL;
    this->rightWg=NULL;
    //this->firstChildTB=NULL;
    this->parentWg=NULL;

    //    this->textW->setGeometry(0,0,this->width()/2,this->height());
    //    this->textW->setVisible(false);

    this->ifTop=false;
    this->adjustName="";
    this->adjValueDefault=0;
    this->functionType = NONE;
    this->adjMaxVal=0;
    this->adjMinVal=0;
    this->dynamicID=0;

    this->installEventFilter(this);
    this->setAutoRaise(true);
    this->setAutoFillBackground(false);




#ifndef DESK_TOP_RUN
    //38.38.44
    pressedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 38pt;";
    normalStyle = "border-image: url(:/new/prefix1/button_normal.png);font:bold 38pt;";
    //focusedStyle = "border-image: url(:/new/prefix1/button_active.png);font:bold 44pt;";
    focusedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 44pt;";
#else
   //12.12.16
    pressedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 12pt;";
    normalStyle = "border-image: url(:/new/prefix1/button_normal.png);font:bold 12pt;";
    //focusedStyle = "border-image: url(:/new/prefix1/button_active.png);font:bold 16pt;";
    focusedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 16pt;";
#endif

    this->setStyleNormal();

    //this->setVisible(true);

    this->textW = new QLabel(this);
    //this->textW->setAlignment(Qt::AlignLeft);
    //    this->textW->setStyleSheet("border-image:none;background-color:rgb(0,0,0,0);text-align:left");
    //    this->textW->setGeometry(0,0,this->width()*3/5,this->height());
    //    this->textW->setText(this->adjustName);
    //    this->textW->setAlignment(Qt::AlignLeft);

    this->textW->setVisible(false);




    this->valProg = new QProgressBar(this);
    this->valProg->setAlignment(Qt::AlignRight);
    //this->valProg->setGeometry( );
    /*
    QPalette pp;
    pp.setColor(QPalette::Background,QColor(0,0,0,0));
    this->valProg->setPalette(pp);*/
    this->valProg->setVisible(false);
    my_Permissions = false;

    //connect( this,SIGNAL(BTPressEvent()), this->dp,SIGNAL(buttonPress()));

}

MyToolButton::~MyToolButton()
{
    delete this->leftWg;
    delete this->rightWg;
    //delete this->childWgs;
    delete this->upWg;
    delete this->downWg;

    delete this->parentWg;
    delete this->valProg;
    delete this->textW;
    //delete this;
}

void MyToolButton::GetIniCfgVal()
{
    switch(this->functionType )
    {
        case PUSHAMOUNT :
            this->adjCurrentVal = this->dp->getIniItemVal("PushAmmount");
            break;
        case PUSHSPEED :
            this->adjCurrentVal = this->dp->getIniItemVal("PushSpeed");
            break;
        case FACEANGLE :
            this->adjCurrentVal = this->dp->getIniItemVal("FaceAngle");
            break;
        case SINGLEPRETIME :
            this->adjCurrentVal = this->dp->getIniItemVal("SinglePreMeltTime");
            break;
        case SINGLEPREINTENSE :
            this->adjCurrentVal = this->dp->getIniItemVal("SinglePreMeltIntense");
            break;
        case SINGLETIME :
            this->adjCurrentVal = this->dp->getIniItemVal("SingleMeltTime");
            break;
        case SINGLEINTENSE :
            this->adjCurrentVal = this->dp->getIniItemVal("SingleMeltIntense");
            break;
        case MULTIPRETIME :
            this->adjCurrentVal = this->dp->getIniItemVal("MultiPreMeltTime");
            break;
        case MULTIPREINTENSE :
            this->adjCurrentVal = this->dp->getIniItemVal("MultiPreMeltIntense");
            break;
        case MULTITIME :
            this->adjCurrentVal = this->dp->getIniItemVal("MultiMeltTime");
            break;
        case MULTIINTENSE :
            this->adjCurrentVal = this->dp->getIniItemVal("MultiMeltIntense");
            break;
        case HEATINGTIME :
            this->adjCurrentVal = this->dp->getIniItemVal("HeatingTime");
            break;
        case MANUALSPEED :
            this->adjCurrentVal = this->dp->getIniItemVal("ManualSpeed");
            break;
        case PARAMSET:
            this->adjCurrentVal = this->dp->getIniItemVal("ParamSel");
            break;
        case MENUALPHA :
            this->adjCurrentVal = this->dp->getIniItemVal("BackLight");
            break;
        case DISCHARGINGCALIB :
            this->adjCurrentVal = this->dp->getIniItemVal("DischargingTime");
            break;
        case STANDBY :
            this->adjCurrentVal = this->dp->getIniItemVal("StandBy");
            break;
        case POWEROFF :
            this->adjCurrentVal = this->dp->getIniItemVal("TurnOff");
            break;
        case TENSIONTES:
            this->adjCurrentVal = this->dp->getIniItemVal("TensionTest");
            break;
        case VLIGHT:
            this->adjCurrentVal = this->dp->getIniItemVal("Vtype");
        break;
        default:
            break;
    }

//    if(this->adjCurrentVal+this->interval <= this->adjMaxVal)
//    {
//        this->adjCurrentVal=this->adjCurrentVal+this->interval;
//        this->valProg->setValue(this->adjCurrentVal);
//    }
}

/*!
 * \brief MyToolButton::SetIniCfgVal
 * 实时修改参数，并写入到配置文件中
 */
void MyToolButton::SetIniCfgVal()
{
    switch(this->functionType )
    {
        case PUSHAMOUNT :
            this->dp->setIniItem("PushAmmount",this->adjCurrentVal);
            break;
        case PUSHSPEED :
            this->dp->setIniItem("PushSpeed",this->adjCurrentVal);
            break;
        case FACEANGLE :
            this->dp->setIniItem("FaceAngle",this->adjCurrentVal);
            break;
        case SINGLEPRETIME :
            this->dp->setIniItem("SinglePreMeltTime",this->adjCurrentVal);
            break;
        case SINGLEPREINTENSE :
            this->dp->setIniItem("SinglePreMeltIntense",this->adjCurrentVal);
            break;
        case SINGLETIME :
            this->dp->setIniItem("SingleMeltTime",this->adjCurrentVal);
            break;
        case SINGLEINTENSE :
            this->dp->setIniItem("SingleMeltIntense",this->adjCurrentVal);
            break;
        case MULTIPRETIME :
            this->dp->setIniItem("MultiPreMeltTime",this->adjCurrentVal);
            break;
        case MULTIPREINTENSE :
            this->dp->setIniItem("MultiPreMeltIntense",this->adjCurrentVal);
            break;
        case MULTITIME :
            this->dp->setIniItem("MultiMeltTime",this->adjCurrentVal);
            break;
        case MULTIINTENSE :
            this->dp->setIniItem("MultiMeltIntense",this->adjCurrentVal);
            break;
        case HEATINGTIME :
            this->dp->setIniItem("HeatingTime",this->adjCurrentVal);
            break;
        case PARAMSET :
            this->dp->setIniItem("ParamSel",this->adjCurrentVal);
            break;
        case MANUALSPEED :
            this->dp->setIniItem("ManualSpeed",this->adjCurrentVal);
            break;
        case MENUALPHA :
            this->dp->setIniItem("BackLight",this->adjCurrentVal);
            break;
        case DISCHARGINGCALIB :
            this->dp->setIniItem("DischargingTime",this->adjCurrentVal);
            break;
        case STANDBY :
            this->dp->setIniItem("StandBy",this->adjCurrentVal);
            this->dp->SetStandBy(this->adjCurrentVal);
            break;
        case POWEROFF :
            this->dp->setIniItem("TurnOff",this->adjCurrentVal);
            this->dp->SetPwrOff(this->adjCurrentVal);
            break;
        case TENSIONTES:
            this->dp->setIniItem("TensionTest",this->adjCurrentVal);
            this->dp->setRetValue("TensionTest");
            break;
        case VLIGHT:
            this->dp->setIniItem("Vtype",this->adjCurrentVal);
            break;
        default:
            break;
    }
}

bool MyToolButton::eventFilter(QObject *obj, QEvent *e)
{
    if(obj==this)
    {
        if(this->ifTop)
        {
        #ifndef DESK_TOP_RUN
            //42,42,48
            pressedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 42pt;";
            normalStyle = "border-image: url(:/new/prefix1/button_normal.png);font:bold 42pt;";
            focusedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 44pt;";
        #else
            //42,42,48
            pressedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 16pt;";
            normalStyle = "border-image: url(:/new/prefix1/button_normal.png);font:bold 16pt;";
            focusedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 20pt;";
        #endif
        }
    }
    if(obj==this&&e->type()==QEvent::Paint){
        if(this->adjustName!="")
        {
            if(this->ifTop)
            {
            #ifndef DESK_TOP_RUN
                //42,42,48
                pressedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 42pt;";
                normalStyle = "border-image: url(:/new/prefix1/button_normal.png);font:bold 42pt;";
                focusedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 44pt;";
            #else
                //16,16,20
                pressedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 8pt;";
                normalStyle = "border-image: url(:/new/prefix1/button_normal.png);font:bold 8pt;";
                focusedStyle = "border-image: url(:/new/prefix1/button_pressed.png);font:bold 10pt;";
            #endif
            }
            //this->setText("xxx");
            this->textW->setStyleSheet("border-image:none;background-color:rgb(0,0,0,0);text-align:left");
            this->textW->setGeometry(10,0,this->width()*3/5,this->height());
            this->textW->setText(this->adjustName);
            this->textW->setAlignment(Qt::AlignVCenter);
            this->textW->setPalette(this->palette());

            //this->textW->setPalette(this->palette());

            this->textW->setVisible(true);
            QPalette p = this->valProg->palette();
            p.setColor(QPalette::Foreground,Qt::black);
            this->valProg->setPalette(p);
            this->valProg->setFormat("%v");
            this->valProg->setAlignment(Qt::AlignCenter);
            this->valProg->setStyleSheet("QProgressBar{border:1px solid black;border-radius:5px;border-image:none;background-color:white;text-align:center;}QProgressBar::chunk { font:black;border-radius:5px;background-color: orange;text-align:center;}");
            if(this->hasFocus())
                this->valProg->setGeometry(this->width()*3/5+8,this->height()/4,50,this->height()/2);

            else
                this->valProg->setGeometry(this->width()*3/5+8,this->height()/4,47,this->height()/2);

            this->valProg->setMaximum(this->adjMaxVal);
            this->valProg->setMinimum(this->adjMinVal);


            //这句很重要，如果在eventFilter过滤出的paintEvent中有显示内容的改变（通过按键改变了显示值），那么会认为是从paintEvent外部进行绘制
            //从而导致painter不处在激活状态导致调用可能不安全
            //此处的解决办法是：只有第一次paint的时候，也就是default和current是一样的值的时候，才在此处setValue。按键事件改变值的时候
            //直接在重载函数中setValue，这样既改变了current的值用于fpga，又改变了显示的值并且还是安全操作。
            if(this->adjCurrentVal==this->adjValueDefault)
                this->valProg->setValue(this->adjValueDefault);
            this->valProg->setVisible(true);

            //        if(this->hasFocus())
            //        {
            //            QPalette p=this->palette();
            //            p.setColor(QPalette::ButtonText,Qt::white);
            //            this->setPalette(p);
            //        }
            return false;
        }
        else {
            if(((MyToolButton *)this->parentWg)->getChildSelected() == this){

            }
        }
    }

    return QWidget::eventFilter(obj,e);
}

QWidget * MyToolButton::getChildSelected()
{
    return this->slectedChildWg;
}

void MyToolButton::setChildSelected(QWidget * selWg)
{
    this->slectedChildWg = selWg;
}

void MyToolButton::setDataProvider(DataProvider* dp)
{
    this->dp = dp;
}

void MyToolButton::setInitial(QString txt, qreal min,qreal max, qreal val,qreal interval)
{
    this->adjustName = txt;
    this->adjValueDefault = val;
    this->adjCurrentVal =val;
    this->adjMaxVal=max;
    this->adjMinVal=min;
    this->interval = interval;
}

void MyToolButton::setStyleFocused()
{

    this->setStyleSheet(this->focusedStyle);

    QPalette p=this->palette();
    //p.setColor(QPalette::ButtonText/*,Qt::white*/);

    this->setPalette(p);

}
void MyToolButton::setStyleNormal()
{

    this->setStyleSheet(this->normalStyle);
    QPalette p;
    p.setColor(QPalette::ButtonText,Qt::black);
    this->setPalette(p);
}
void MyToolButton::setStylePressed()
{
    if(dynamicID > 20){
        this->dp->UIChange(dynamicID);
        //qDebug() << "ecmit refreshID " << dynamicID << __FILE__<<__LINE__;
    }
    this->setStyleSheet(this->pressedStyle);
    //emit this->currentButton( dynamicID);
}
void MyToolButton::setStyleNone()
{
    this->setStyleSheet("border-image:none");
}
void MyToolButton::setRightWg(QWidget *tb)
{
    this->rightWg = tb;
}
void MyToolButton::setLeftWg(QWidget *tb)
{
    this->leftWg = tb;
}
void MyToolButton::setUpWg(QWidget *tb)
{
    this->upWg = tb;
}
void MyToolButton::setDownWg(QWidget *tb)
{
    this->downWg = tb;
}
void MyToolButton::setStyleChecked(bool ischecked)
{
    if(ischecked == true){

    }
}
void MyToolButton::setParentWg(QWidget *tb)
{
    this->parentWg = tb;
}
//字按钮，自动传递dataprovider指针,所以要在执行此句之前设置好父按钮的DataProvider
void MyToolButton::addChildWg(QWidget *tb)
{
    this->childWgs.append(tb);
    ((MyToolButton*)tb)->setParentWg(this);
    ((MyToolButton*)tb)->setDataProvider(this->dp);
}
void MyToolButton::focusChild()
{

    if(this->childWgs.empty()) return;

    switch(dynamicID){
        case 1:
        case 4:
        case 11:
        case 12:
        case 13:
            this->dp->UIChange(dynamicID);
            break;
        default:
            break;
    }

    this->childWgs.at(0)->setFocus();


}
void MyToolButton::focusUp()
{
    if(this->dynamicID == 2) this->dp->UIChange(dynamicID);
    if(this->upWg==NULL) return;
    this->upWg->setFocus();
}
void MyToolButton::focusDown()
{
    if(this->dynamicID == 3) this->dp->UIChange(dynamicID);
    if(this->downWg==NULL)  return;
    this->downWg->setFocus();
}
void MyToolButton::focusLeft()
{
    if(this->leftWg==NULL) return;
    this->leftWg->setFocus();
}
void MyToolButton::focusRight()
{
    if(this->rightWg==NULL)  return;
    this->rightWg->setFocus();
}
void MyToolButton::focusParent()
{
    if(this->parentWg==NULL) return;
    this->parentWg->setFocus();
}
void MyToolButton::setFunctionType(FunctionButtonType type)
{
    this->functionType = type;
}

void MyToolButton::focusInEvent(QFocusEvent *e)
{
    this->setStyleFocused();
}

void MyToolButton::focusOutEvent(QFocusEvent *e)
{
    this->setStyleNormal();
}


//显示按钮菜单的子按钮
void MyToolButton::showChildWgs(bool vis)
{
    foreach(QWidget* t, this->childWgs)
    {

        t->setVisible(vis);

        //((MyToolButton*)t)->GetIniCfgVal();
    }
}

void MyToolButton::setChildDisabled(bool enable)
{
    foreach(QWidget* t, this->childWgs)
    {
        qDebug() << t << __FILE__ <<__LINE__;
        t->setDisabled(enable);
    }
}

void MyToolButton::setIfTop(bool ifTop)
{
    this->ifTop = ifTop;
}

void MyToolButton::setCurVal(unsigned int val)
{
    if((val <= this->adjMaxVal)&&(val >= this->adjMinVal))
    {
        this->adjCurrentVal = val;
        this->valProg->setValue(this->adjCurrentVal);
    }
}

void MyToolButton::keyPressEvent(QKeyEvent *e)
{

    this->dp->btPressEvent();
    QKeyEvent* ke = (QKeyEvent*)e;
    this->dp->SetFusionReg(rBEEP_ON  ,1*1000*10000);

    if(ke->key()==Qt::Key_Right)
    {
        if( !my_Permissions )
        {
            if(this->adjCurrentVal+this->interval<=this->adjMaxVal)
            {
                this->adjCurrentVal=this->adjCurrentVal+this->interval;
                this->valProg->setValue(this->adjCurrentVal);
                this->SetIniCfgVal();
            }
            this->focusLeft();
            this->focusRight();

        }else {
            my_Password += "2";
        }


    }
    else if(ke->key() == Qt::Key_Left)
    {
        if( !my_Permissions )
        {
            if(this->adjCurrentVal-this->interval>=this->adjMinVal)
            {
                this->adjCurrentVal=this->adjCurrentVal-this->interval;
                this->valProg->setValue(this->adjCurrentVal);
                this->SetIniCfgVal();
            }
                  this->focusLeft();

        }else{
               my_Password += "1";
        }



    }
    else if(ke->key()== Qt::Key_Up)
    {
        if( !my_Permissions )
        {
             this->focusUp();
        }else{
            my_Password += "3";
        }


    }
    else if(ke->key() == Qt::Key_Down)
    {
        if( !my_Permissions )
        {
            this->focusDown();
        }else{
              my_Password += "4";
        }



    }
    else if(ke->key() == Qt::Key_Q)
    {
        if( my_Permissions )
        {
            //输入组合密码
           my_keyDisenable = true;
           my_Password.clear();
        }

        //调用相应的fpga响应函数
        this->enterFunction();
        this->setStylePressed();
        this->showChildWgs(true);
        this->focusChild();

    }
    else if(ke->key()==Qt::Key_Shift)
    {

            if(this->parentWg!=NULL)
            {
                if(!this->ifTop)
                    ((MyToolButton*)this->parentWg)->showChildWgs(false);
                this->parentWg->setVisible(true);
                this->focusParent();
            }
            my_keyDisenable = false;
            if(this->functionType == HEATINGTIME) this->dp->UpdateHeatTime((this->adjCurrentVal)*1000);
    }

    //qDebug() << my_Password <<__FILE__<<__LINE__;
    if ( my_Password == "4321")
     //   if ( my_Password == "1234")
    {
       my_Permissions = false;
       my_Password.clear();
       this->setChildDisabled(false);
       this->enterFunction();
       this->setStylePressed();
       this->showChildWgs(true);
       this->focusChild();
       my_keyDisenable = false;
       //qDebug() << this->parentWg  <<__FILE__<<__LINE__;
      emit this->Unlock(  );
    }


}
void MyToolButton::setRootWindow(QMainWindow *mw)
{
    this->rootWin = mw;
}

void MyToolButton::setDynamicID(int id)
{
    this->dynamicID = id;
}

void MyToolButton::setMyDisplayWg(MyDisplayWidget *mdwg)
{
    this->mdwg = mdwg;
}

void MyToolButton::keyReleaseEvent(QKeyEvent *e)
{
    if(((QKeyEvent*)e)->key()==Qt::Key_R)
    {
        this->setStyleFocused();
    }
}
void MyToolButton::enterFunction()
{
    switch(this->functionType)
    {      
        case AUTOMODE:
            this->dp->setMeltMode(Auto);
            break;
        case MANUALMODE:
            this->dp->setMeltMode(Manual);
            break;
        case PAUSEMODE3:
            this->dp->setMeltMode(Pause3);
            break;
        case PAUSEMODE2:
            this->dp->setMeltMode(Pause2);
            break;
        case PAUSEMODE1:
            this->dp->setMeltMode(Pause1);
            break;
        case DISCHARGINGCALIB:
            this->dp->setMeltMode(Calibe);
            break;
        case AUTOHEAT:
            dp->setHeatingMode(AutoHeating);
            dp->UpdateHeatMode(AutoHeating);
            break;
        case MANUALHEAT:
            dp->setHeatingMode(ManualHeating);
            dp->UpdateHeatMode(ManualHeating);
            break;
            //Menu3
        case QUICKMODE:
            dp->setSpeedMode(Fast);           
            break;
        case PRECISEMODE:
            dp->setSpeedMode(Precise);
            break;
        case TENSIONTESTON:
            dp->setIniItem("ElastTest",1);
            break;
        case TENSIONTESTOFF:
            dp->setIniItem("ElastTest",0);
            break;
        case VLIGHTON:
            dp->setVLight(LightOn);
            break;
        case VLIGHTOFF:
            dp->setVLight(LightOff);
            break;
        case CHANGEPOLE:
            break;
        case DUSTDETECT:
            break;
        case SELFCHECK:
            break;
        case SYSINFO:
            break;
        default:
            break;
    }
}




FunctionButtonType MyToolButton::getFunctionButtonType()
{
    return functionType;
}


//! 添加 选中菜单中的打勾标识 lbs-2017/4/26
void MyToolButton::setupSelectedButton()
{
    this->selectICO = new QLabel(this);
    this->selectICO->setGeometry(10,3,20,25);
    this->selectICO->setScaledContents(true);
    this->selectICO->setStyleSheet("border-image: url(:/new/prefix1/button_select.png);background-color:rgb(0,0,0,0)");
}

void MyToolButton::setSelected(bool enable)
{
    if( enable ){
        this->selectICO->show();
    }else{
        this->selectICO->hide();
    }
}


// true 加载权限  false 解除权限
void MyToolButton::setPerm(bool enable)
{
    my_Permissions = enable;

    if( !enable )
    {
        my_Permissions = false;
        my_Password.clear();
        my_keyDisenable = false;
    }
}


